package com.anji.plus.gaea.introspector;

import com.anji.plus.gaea.constant.GaeaConstant;
import com.anji.plus.gaea.holder.UserContentHolder;
import com.anji.plus.gaea.utils.GaeaDateUtils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

/**
 * 后端接收参数 反序列化
 * @author: Raod
 * @since: 2021-12-16
 */
public class DateDeSerializer extends JsonDeserializer<Date> {

    private static Logger logger = LoggerFactory.getLogger(DateDeSerializer.class);

    private final String pattern;

    public DateDeSerializer(String pattern) {
        super();
        this.pattern = pattern;
    }

    @Override
    public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String text = p.getText().trim();
        if (StringUtils.isBlank(text)) {
            return null;
        }
        if (text.matches(GaeaConstant.TIME_MILLIS_REGEX)) {
            //feign调用默认拿到的是13位时间戳字符串
            return GaeaDateUtils.timeMillisToDate(text);
        }
        TimeZone timeZone;
        if (StringUtils.isNotBlank(UserContentHolder.getTimeZone())) {
            timeZone = TimeZone.getTimeZone(UserContentHolder.getTimeZone());
        }else {
            timeZone = TimeZone.getDefault();
        }
        //针对yyyy-MM或者yyyy-MM-dd这种，不做时区转换
        if (GaeaConstant.MOUTH_PATTERN.equals(pattern) || GaeaConstant.DATE_PATTERN.equals(pattern)) {
            return GaeaDateUtils.StringToDate(text, pattern);
        }
        //将浏览器访问时区转化为java机器所在时区
        return GaeaDateUtils.sourceTimeZoneToTargetTimeZone(text, pattern, timeZone, TimeZone.getDefault());
    }
}
